<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '登录',
  },
}
</route>

<script lang="ts" setup>
import {
  useUserCenterLoginMutation,
  useUserCenterRequestSmsMutation,
} from '@/service/app/userCenter.vuequery'
import { useUserStore } from '@/store/user'

defineOptions({
  name: 'Login',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 表单数据
const formData = ref({
  phone: '',
  code: '',
})

// 协议同意状态
const agreedToTerms = ref(false)

// 表单验证
const formErrors = ref<Record<string, string>>({})
const isSubmitting = ref(false)
const countdown = ref(0)

// SMS 请求 mutation
const {
  mutate: requestSms,
  isPending: smsLoading,
  error: smsError,
} = useUserCenterRequestSmsMutation({
  onSuccess: (data) => {
    console.log('SMS 请求成功:', data)
    uni.showToast({
      title: '验证码已发送',
      icon: 'success',
    })

    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  },
  onError: (error) => {
    console.error('SMS 请求失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'error',
    })
  },
})

// 登录 mutation
const {
  mutate: loginUser,
  isPending: loginLoading,
  error: loginError,
} = useUserCenterLoginMutation({
  onSuccess: (response) => {
    console.log('登录成功响应:', response)

    // 检查响应是否成功
    if (!response.success) {
      console.error('登录失败:', response.message)
      uni.showToast({
        title: response.message || '登录失败',
        icon: 'error',
      })
      isSubmitting.value = false
      return
    }

    // 使用store的登录方法处理登录成功
    const userStore = useUserStore()

    // 直接使用登录接口返回的数据设置用户信息
    if (response.data) {
      const loginData = response.data
      const userInfo = {
        id: Number(loginData.id || 0),
        username: loginData.mobile || formData.value.phone, // 使用手机号作为用户名
        avatar: '/static/images/default-avatar.png', // 登录接口不返回头像，使用默认头像
        token: loginData.token || '',
      }

      console.log('设置用户信息:', userInfo)
      // 只使用store方法设置用户信息，让Pinia持久化插件自动处理本地存储
      userStore.setUserInfo(userInfo)

      // 验证token是否正确保存
      console.log('登录后store中的用户信息:', userStore.userInfo)
      console.log('登录后本地存储的token:', uni.getStorageSync('token'))
    }

    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })

    // 延迟跳转
    setTimeout(() => {
      handleLoginSuccess()
    }, 1500)
  },
  onError: (error) => {
    console.error('登录失败:', error)
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'error',
    })
    isSubmitting.value = false
  },
})

// 发送验证码
async function sendCode() {
  if (!formData.value.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
    })
    return
  }

  // 调用 SMS API
  requestSms({
    params: {
      mobile: formData.value.phone,
    },
  })
}

// 登录
async function handleLogin() {
  if (!validateForm()) {
    return
  }

  if (!agreedToTerms.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none',
    })
    return
  }

  isSubmitting.value = true

  // 调用真正的登录API
  loginUser({
    body: {
      mobile: formData.value.phone,
      code: formData.value.code,
    },
  })
}

// 登录成功后的跳转逻辑
function handleLoginSuccess() {
  console.log('开始处理登录成功跳转...')

  try {
    // 检查是否有重定向URL
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = (currentPage as any).options || {}
    const redirectUrl = options.redirect

    console.log('当前页面选项:', options)
    console.log('重定向URL:', redirectUrl)

    if (redirectUrl) {
      // 如果有重定向URL，跳转到指定页面
      const decodedUrl = decodeURIComponent(redirectUrl)
      console.log('重定向到:', decodedUrl)

      // 使用redirectTo跳转到目标页面
      console.log('使用redirectTo跳转到页面:', decodedUrl)
      uni.redirectTo({
        url: decodedUrl,
        success: () => {
          console.log('redirectTo成功')
          isSubmitting.value = false
        },
        fail: (err) => {
          console.error('redirectTo失败:', err)
          // 如果redirectTo失败，尝试跳转到首页
          console.log('redirectTo失败，尝试跳转到首页')
          uni.redirectTo({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转首页成功')
              isSubmitting.value = false
            },
            fail: (redirectErr) => {
              console.error('跳转首页也失败:', redirectErr)
              isSubmitting.value = false
            },
          })
        },
      })
    }
    else {
      // 否则跳转到首页
      console.log('跳转到首页')
      uni.redirectTo({
        url: '/pages/index/index',
        success: () => {
          console.log('跳转首页成功')
          isSubmitting.value = false
        },
        fail: (err) => {
          console.error('跳转首页失败:', err)
          isSubmitting.value = false
        },
      })
    }
  }
  catch (error) {
    console.error('跳转过程中发生错误:', error)
    // 如果出错，尝试直接跳转到首页
    uni.redirectTo({
      url: '/pages/index/index',
      success: () => {
        console.log('异常情况下的跳转成功')
        isSubmitting.value = false
      },
      fail: (err) => {
        console.error('异常情况下的跳转也失败:', err)
        isSubmitting.value = false
      },
    })
  }
}

// 表单验证
function validateForm() {
  formErrors.value = {}

  if (!formData.value.phone.trim()) {
    formErrors.value.phone = '请输入手机号'
  }
  else if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    formErrors.value.phone = '请输入正确的手机号'
  }

  if (!formData.value.code.trim()) {
    formErrors.value.code = '请输入验证码'
  }
  else if (formData.value.code.length !== 6) {
    formErrors.value.code = '验证码应为6位数字'
  }

  return Object.keys(formErrors.value).length === 0
}

// 用户协议和隐私政策
function goToUserAgreement() {
  uni.showToast({
    title: '用户协议',
    icon: 'none',
  })
}

function goToPrivacyPolicy() {
  uni.showToast({
    title: '隐私政策',
    icon: 'none',
  })
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 切换协议同意状态
function toggleAgreement() {
  agreedToTerms.value = !agreedToTerms.value
}
</script>

<template>
  <view
    class="min-h-screen"
    :style="{
      marginTop: `${safeAreaInsets?.top}px`,
      background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)',
    }"
  >
    <!-- 关闭按钮 -->
    <view class="absolute left-4 top-4 z-10">
      <view
        class="h-10 w-10 flex items-center justify-center rounded-full bg-white bg-opacity-20"
        @click="goBack"
      >
        <text class="i-carbon-close text-xl text-white" />
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="min-h-screen flex flex-col items-center justify-center px-6">
      <!-- 欢迎文字 -->
      <view class="mb-12 text-center">
        <view class="mb-2 text-3xl text-gray-800 font-bold">
          欢迎来到
        </view>
        <view class="text-3xl text-gray-800 font-bold">
          检测认证公示中心
        </view>
      </view>

      <!-- 登录表单 -->
      <view class="max-w-sm w-full">
        <!-- 手机号输入 -->
        <view class="mb-6">
          <input
            v-model="formData.phone"
            placeholder="请输入手机号"
            type="number"
            class="w-full border-2 border-gray-200 rounded-xl bg-white px-4 py-4 text-lg"
            :class="{ 'border-red-500': formErrors.phone }"
          >
          <view v-if="formErrors.phone" class="mt-2 text-sm text-red-500">
            {{ formErrors.phone }}
          </view>
        </view>

        <!-- 验证码输入 -->
        <view class="mb-6">
          <view class="flex space-x-3">
            <input
              v-model="formData.code"
              placeholder="验证码"
              type="number"
              class="flex-1 border-2 border-gray-200 rounded-xl bg-white px-4 py-4 text-lg"
              :class="{ 'border-red-500': formErrors.code }"
            >
            <view
              class="flex items-center border-2 border-blue-500 rounded-xl bg-blue-500 px-6 py-4"
              :class="{ 'opacity-50': countdown > 0 || smsLoading }"
              @click="countdown === 0 && !smsLoading ? sendCode() : null"
            >
              <text class="text-white font-medium">
                {{ smsLoading ? '发送中...' : countdown > 0 ? `${countdown}s` : '发送验证码' }}
              </text>
            </view>
          </view>
          <view v-if="formErrors.code" class="mt-2 text-sm text-red-500">
            {{ formErrors.code }}
          </view>
        </view>

        <!-- 用户协议 -->
        <view class="mb-8 flex items-start">
          <view class="mr-3 mt-1" @click="toggleAgreement">
            <text
              class="text-xl"
              :class="
                agreedToTerms
                  ? 'i-carbon-checkbox-checked text-blue-500'
                  : 'i-carbon-checkbox text-gray-400'
              "
            />
          </view>
          <view class="flex-1 text-sm text-gray-600">
            已阅读同意
            <text class="text-blue-500" @click="goToUserAgreement">
              《用户协议》
            </text>
            和
            <text class="text-blue-500" @click="goToPrivacyPolicy">
              《隐私政策》
            </text>
            ，未注册的手机号将自动创建账号。
          </view>
        </view>

        <!-- 登录按钮 -->
        <view
          class="w-full rounded-xl bg-blue-500 py-4 text-center"
          :class="{ 'opacity-50': isSubmitting || loginLoading }"
          @click="handleLogin"
        >
          <text class="text-lg text-white font-medium">
            {{ isSubmitting || loginLoading ? '登录中...' : '立即登录' }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>
